package com.ruoyi.project.system.customer.deal.controller;

import java.math.BigDecimal;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.coinrecord.domain.HaoqiCoinRecord;
import com.ruoyi.project.system.coinrecord.dto.HaoqiCoinRecordDto;
import com.ruoyi.project.system.coinrecord.service.IHaoqiCoinRecordService;
import com.ruoyi.project.system.customer.customer.domain.Customer;
import com.ruoyi.project.system.customer.customer.service.ICustomerService;
import com.ruoyi.project.system.customer.deal.domain.CustomerDeal;
import com.ruoyi.project.system.customer.deal.service.ICustomerDealService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.house.house.domain.House;
import com.ruoyi.project.system.house.house.enums.HouseDto;
import com.ruoyi.project.system.house.house.service.IHouseService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.paylog.domain.PayLog;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import com.ruoyi.project.system.shopconfig.domain.ShopConfig;
import com.ruoyi.project.system.shopconfig.service.IShopConfigService;

/**
 * 客户成交Controller
 * 
 * @author f_baisi
 * @date 2020-08-29
 */
@Controller
@RequestMapping("/system/customer/deal")
public class CustomerDealController extends BaseController
{
    private String prefix = "system/customer/deal";

    @Autowired
    private ICustomerDealService customerDealService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IHaoqiCoinRecordService haoqiCoinRecordService;

    @Autowired
    private IShopConfigService shopConfigService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IPayLogService payLogService;

    @RequiresPermissions("system/customer:customer.deal:view")
    @GetMapping()
    public String deal()
    {
        return prefix + "/deal";
    }

    /**
     * 查询客户成交列表
     */
    @RequiresPermissions("system/customer:customer.deal:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CustomerDeal customerDeal)
    {
        startPage();
        List<CustomerDeal> list = customerDealService.selectCustomerDealList(customerDeal);
        return getDataTable(list);
    }

    /**
     * 导出客户成交列表
     */
    @RequiresPermissions("system/customer:customer.deal:export")
    @Log(title = "客户成交", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CustomerDeal customerDeal)
    {
        List<CustomerDeal> list = customerDealService.selectCustomerDealList(customerDeal);
        ExcelUtil<CustomerDeal> util = new ExcelUtil<CustomerDeal>(CustomerDeal.class);
        return util.exportExcel(list, "deal");
    }

    /**
     * 新增客户成交
     */
    @GetMapping("/add")
    public String add(ModelMap map)
    {
        map.put("customerList",this.customerService.selectCustomerList(null));
        House house = new House();
        house.setStatus(1);
        map.put("houseList",this.houseService.selectHouseList(house));
        return prefix + "/add";
    }

    /**
     * 新增保存客户成交
     */
    @RequiresPermissions("system/customer:customer.deal:add")
    @Log(title = "客户成交", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(CustomerDeal customerDeal)
    {
        //添加成交信息
        customerDealService.insertCustomerDeal(customerDeal);
        //查询房源信息
        HouseDto houseDto = this.houseService.selectHouseById(customerDeal.getHouseId());

        //客户添加人返
        Customer customer = this.customerService.selectCustomerById(customerDeal.getCustomerId());
        if(customer.getMemberId()!=null){
            //查询当前用户
            Member member = this.memberService.selectMemberById(customer.getMemberId());
//            this.haoqiCoinRecordService.returnPrice(customer.getMemberId(),customerDeal.getPrice(),customer.getId(),1);
            //查询返费比例
            ShopConfig shopConfig = this.shopConfigService.findAll().get(0);
            //用户应得金额
            BigDecimal bili = null;
            if(member.getIsInside()==0){
                bili=shopConfig.getOutVipReturnRatio();
            }else{
                bili=shopConfig.getVipReturnRatio();
            }
            BigDecimal one = customerDeal.getPrice().multiply(bili).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            //添加记录
            HaoqiCoinRecord haoqiCoinRecord = new HaoqiCoinRecord();
            haoqiCoinRecord.setResId(customer.getId());
            haoqiCoinRecord.setType(0);
            haoqiCoinRecord.setGetType(1);
            haoqiCoinRecord.setNum(one);
            haoqiCoinRecord.setMemberId(member.getId());
            haoqiCoinRecord.setCreated(DateUtils.getNowDate());
            haoqiCoinRecord.setStatus(1);
            this.haoqiCoinRecordService.insertHaoqiCoinRecord(haoqiCoinRecord);
            //更新用户余额
            Member update = new Member();
            update.setId(member.getId());
            update.setHaoqiCoin(member.getHaoqiCoin().add(one));
            this.memberService.updateMember(update);
            //查询该用户成为联盟商时支出多少
            PayLog payLog = new PayLog();
            payLog.setStatus(1);
            payLog.setMemberId(member.getId());
            List<PayLog> payLogs = this.payLogService.selectPayLogList(payLog);
            if(payLogs.size()!=0){
                //判断该用户返费次数是否达到10次
                HaoqiCoinRecord select = new HaoqiCoinRecord();
                select.setMemberId(member.getId());
                select.setType(0);
                select.setGetType(2);
                List<HaoqiCoinRecordDto> haoqiCoinRecordDtos = this.haoqiCoinRecordService.selectHaoqiCoinRecordList(select);
                //未达到十次 就进行会员费用返费
                if(haoqiCoinRecordDtos.size()<10){
                    //生成收益记录
                    HaoqiCoinRecord record = new HaoqiCoinRecord();
                    record.setGetType(2);
                    record.setType(0);
                    record.setMemberId(member.getId());
                    record.setCreated(DateUtils.getNowDate());
                    record.setStatus(1);
                    record.setResId(member.getId());
                    record.setNum(payLogs.get(0).getPrice().multiply(new BigDecimal(0.1)));
                    this.haoqiCoinRecordService.insertHaoqiCoinRecord(record);
                    //更新用户余额
                    update.setHaoqiCoin(update.getHaoqiCoin().add(record.getNum()));
                    this.memberService.updateMember(update);
                }

            }
        }
        //如果是房源信息 就改为已卖出
        if(houseDto.getType().equals(0)){
            House update = new House();
            update.setId(customerDeal.getHouseId());
            update.setStatus(3);
            this.houseService.updateHouse(update);

            //如果房源是独家房源 就返利
//            if(houseDto.getSole()==1){
//                //房源添加人返
//                if(houseDto.getMemberId()!=null){
//                    this.haoqiCoinRecordService.returnPrice(houseDto.getMemberId(),customerDeal.getPrice(),houseDto.getId(),2);
//                }
//            }
        }
        //成交以后 修改客户信息为已成交
        Customer update = new Customer();
        update.setId(customerDeal.getCustomerId());
        update.setStatus(1);
        this.customerService.updateCustomer(update);
        return AjaxResult.success();
    }

    /**
     * 修改客户成交
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        CustomerDeal customerDeal = customerDealService.selectCustomerDealById(id);
        mmap.put("customerDeal", customerDeal);
        return prefix + "/edit";
    }

    /**
     * 修改保存客户成交
     */
    @RequiresPermissions("system/customer:customer.deal:edit")
    @Log(title = "客户成交", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CustomerDeal customerDeal)
    {
        return toAjax(customerDealService.updateCustomerDeal(customerDeal));
    }

    /**
     * 删除客户成交
     */
    @RequiresPermissions("system/customer:customer.deal:remove")
    @Log(title = "客户成交", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(customerDealService.deleteCustomerDealByIds(ids));
    }
}
